﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using csvm.datamodel.contract;
using csvm.portal.contract;

namespace csvm.portal {
    public partial class UI : Form, IPortal {

        public UI() {
            InitializeComponent();
        }

        public void ProcessProgressChanged(double percent) {
            progressBarFileLoadProgress.Value = (int) percent;
        }

        private void ButtonLoadFileClick(object sender, EventArgs e) {
            ProcessProgressChanged(0.0);

            var openFileDialog = new OpenFileDialog { CheckFileExists = true };
            if (openFileDialog.ShowDialog() != DialogResult.OK)
                return;

            var filename = openFileDialog.FileName;
            ClearListView();
            OnReadFile(filename);
        }

        public void ProcessGetHeader(Record header) {
            foreach (var item in header.Values) {
                listViewCsvData.Columns.Add(item);
            }
        }

        public void ProcessLoadPages(IEnumerable<Page> pages) {
            foreach (var page in pages) {
                FillPage(page);
            }
        }

        private void FillPage(Page page) {
            foreach (var record in page.Records) {
                FillRecord(record);
            }
        }

        private void FillRecord(Record record) {
            var listViewItem = new ListViewItem();
            var isFirstItem = true;
            foreach (var item in record.Values) {
                if (isFirstItem)
                    listViewItem.Text = item;
                else
                    listViewItem.SubItems.Add(item);
                isFirstItem = false;
            }
            listViewCsvData.Items.Add(listViewItem);
        }

        private void ClearListView() {
            listViewCsvData.Items.Clear();
            listViewCsvData.Columns.Clear();
        }

        public event Action<string> OnReadFile;
    }
}
